import {
    Component,
    OnInit,
    Injector,
    ViewChild,
    ChangeDetectorRef,
    ElementRef,
    Output,
    EventEmitter
} from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Base_DataItemServiceProxy, Base_DataItemEditDto } from '@shared/service-proxies/stock-service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';

export interface IDataitemUnitOnEdit {
    id?: number;
    parentId?: number;
    displayName?: string;
    code?: string;
    sortCode?: number;
    remark?: string;
}
@Component({
    selector: 'createOrEditDataItemModal',
    templateUrl: './create-or-edit-dataitem-modal.component.html',
    animations: [appModuleAnimation()]
})
export class CreateOrEditDataItemModalComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        private _baseItemService: Base_DataItemServiceProxy,
        private _changeDetector: ChangeDetectorRef
    ) {
        super(injector);
    }
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('dataitemUnitDisplayName') dataitemUnitDisplayNameInput: ElementRef;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    dataitemUnit: IDataitemUnitOnEdit = {};
    active = false;
    saving = false;

    ngOnInit(): void {}
    onShown(): void {
        document.getElementById('dataitemUnitDisplayName').focus();
    }
    show(dataitemUnit?: IDataitemUnitOnEdit): void {
        this.dataitemUnit = dataitemUnit;
        this.active = true;
        this.modal.show();
        this._changeDetector.detectChanges();
    }
    close(): void {
        this.modal.hide();
        this.active = false;
    }
    save(): void {
        const createInput = new Base_DataItemEditDto();
        createInput.id = this.dataitemUnit.id;
        createInput.f_ParentId = this.dataitemUnit.parentId;
        createInput.f_ItemName = this.dataitemUnit.displayName;
        createInput.f_ItemCode = this.dataitemUnit.code;
        createInput.f_SortCode = this.dataitemUnit.sortCode;
        createInput.f_Remark = this.dataitemUnit.remark;

        this.saving = true;
        this._baseItemService
            .createOrUpdateDataItem(createInput)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(result => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(result);
            });
    }
}
